<!--
* @description 弹出单选
* @author zywu
* @date 2021/03/16 20:49:19
!-->
<template>
  <div class="pop-action">
    <pop-button
      :is-active="!!selected"
      :is-open="active"
      :text="currentText"
      :align="align"
      @click.native="handleClick"
    ></pop-button>
    <van-action-sheet
      ref="action"
      v-model="active"
      :actions="optionsData"
      :cancel-text="cancelText"
      @select="onSelect"
      @cancel="onCancel"
    />
  </div>
</template>

<script>
import PopButton from '@/components/PopButton'
export default {
  props: {
    options: Array,
    text: String,
    defaultValue: [String, Number],
    showSelected: {
      type: Boolean,
      default: true,
    },
    cancelText: {
      type: String,
      require: false,
      default: '清空',
    },
    defaultValue: {
      type: [String, Number],
      default: '',
    },
    align: {
      type: String,
      default: 'center',
    },
  },
  data() {
    return {
      active: false,
      selected: '',
      optionsData: [],
      currentText: '',
    }
  },

  components: { PopButton },

  watch: {
    options() {
      this.optionsData = JSON.parse(JSON.stringify(this.options))
    },
    selected(val) {
      this.optionsData.forEach((n) => {
        this.$set(
          n,
          'className',
          val && n.value == val.value ? 'is-selected' : ''
        )
      })
      if (this.showSelected) {
        this.currentText = val ? val.name : `${this.text}`
      }
    },
    // defaultValue(val) {
    //   if (val) {
    //     this.setSelected(val)
    //   } else {
    //     this.selected = ''
    //   }
    // },
  },

  created() {
    this.currentText = `${this.text}`
    this.optionsData = JSON.parse(JSON.stringify(this.options))
    if (this.defaultValue) {
      this.selected = this.options.filter((n) => {
        return n.value == this.defaultValue
      })[0]
    }
  },

  methods: {
    setSelected(value) {
      this.selected = this.optionsData.filter((n) => {
        return n.value == value
      })[0]
    },
    onSelect(action) {
      this.active = false
      this.selected = action
      this.$emit('change', action)
    },
    handleClick() {
      this.active = !this.active
    },
    onCancel() {
      this.selected = ''
      this.$emit('change', '')
    },
  },
}
</script>
<style lang='scss'>
@import '../styles/variables.scss';
.pop-action {
  .van-action-sheet__item {
    position: relative;
    &::before {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 1px;
      background: #e1e1e1;
      transform: scaleY(0.5);
    }
    // &:last-child {
    //   &::before {
    //     display: none;
    //   }
    // }
    &.is-selected {
      background: #f3f9ff;
      color: $color-theme;
    }
  }
}
</style>